﻿using System.IO;
using Castle.DynamicProxy;
using Framework.Core.Reflection;

namespace Framework.Core.Recorder
{
    internal class DependencyRecorder : IInterceptor
    {
        private readonly IDependencyRepository dependencyRepository;
        private readonly IMethodFactory methodFactory;
        private readonly ICallKeyBuilder callKeyBuilder;

        internal DependencyRecorder(IDependencyRepository dependencyRepository,
            ICallKeyBuilder callKeyBuilder,
            IMethodFactory methodFactory)
        {
            this.dependencyRepository = dependencyRepository;
            this.callKeyBuilder = callKeyBuilder;
            this.methodFactory = methodFactory;
        }

        public void Intercept(IInvocation invocation)
        {
            var method = methodFactory.Create(invocation);

            var recordKey = callKeyBuilder.Build(method);

            invocation.Proceed();

            dependencyRepository.Update(recordKey, new DependencyCall(invocation.ReturnValue, new DependencyParameters(method)));
        }

        public void Serialize(Stream stream)
        {
            dependencyRepository.Serialize(stream);

            if (stream is MemoryStream)
            {
                stream.Seek(0, SeekOrigin.Begin);
            }
        }
    }
}